package com.yoo.ons.function.like

import android.animation.Animator
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.view.animation.AnimationUtils
import android.view.animation.TranslateAnimation
import androidx.lifecycle.ViewModelProvider
import com.gyf.immersionbar.ImmersionBar
import com.yoo.chat.kit.IMCenter
import com.yoo.module_base.R
import com.yoo.module_base.base.BaseDialogFragment
import com.yoo.module_base.utils.setOnClickCallback
import com.yoo.module_base.utils.shake
import com.yoo.ons.databinding.DialogMatchSuccessBinding
import com.yoo.ons.function.MainViewModel
import com.yoo.ons.function.like.viewmodel.WhoLikeMeViewModel
import com.yoo.ons.util.Injections.mainHandler
import com.yoo.ons.util.load
import io.rong.imlib.IRongCallback
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import io.rong.message.TextMessage

/**
 * 匹配成功页面
 */
class MatchSuccessDialogFragment : BaseDialogFragment() {

    private var innerBinding: DialogMatchSuccessBinding? = null
    private val binding get() = innerBinding!!
    private val toUserId by lazy { arguments?.getString(MATCH_SUCCESS_TO_USER_ID)!! }
    private val toUserImg by lazy { arguments?.getString(MATCH_SUCCESS_TO_USER_HEAD)!! }
    private val mainViewModel by lazy {
        ViewModelProvider(requireActivity())[MainViewModel::class.java]
    }
    private val wlmViewModel by lazy {
        ViewModelProvider(requireActivity())[WhoLikeMeViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        innerBinding = innerBinding
            ?: DialogMatchSuccessBinding.inflate(inflater, container, false)
        return binding.root
    }


    override fun setWindow(win: Window) {
        win.setWindowAnimations(R.style.DialogAnimation)
        win.decorView.setPadding(0, 0, 0, 0)
        val lp = win.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.MATCH_PARENT
        win.attributes = lp
        win.setGravity(Gravity.BOTTOM)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mainViewModel.userInfoLiveData.observe(viewLifecycleOwner) {
            binding.imgMatchSuccessOne.load(it.avatarUrl)
            binding.imgMatchSuccessTwo.load(toUserImg)
        }
        binding.imgMatchSuccessClose.setOnClickCallback { dismiss() }
        // 设置动画监听器
        binding.lottieMatchSuccessBg.addAnimatorListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
                // 动画开始时执行的操作
                mainHandler.postDelayed({ showAnim() }, 100)
            }

            override fun onAnimationEnd(animation: Animator) {
                // 动画结束时执行的操作
            }

            override fun onAnimationCancel(animation: Animator) {
                // 动画取消时执行的操作
            }

            override fun onAnimationRepeat(animation: Animator) {
                // 动画重复时执行的操作
            }
        })
        // 启动动画
        binding.lottieMatchSuccessBg.playAnimation()
    }

    private fun setData() {
        binding.txtMatchSuccessBottomEmojiOne.text = String(Character.toChars(0x1F44B))
        binding.txtMatchSuccessBottomEmojiTwo.text = String(Character.toChars(0x1F609))
        binding.txtMatchSuccessBottomEmojiThree.text = String(Character.toChars(0x2764))
        binding.txtMatchSuccessBottomEmojiFour.text = String(Character.toChars(0x1F60D))
        binding.txtMatchSuccessBottomEmojiOne.setOnClickCallback {
            goToChat(it,binding.txtMatchSuccessBottomEmojiOne.text.toString())
        }
        binding.txtMatchSuccessBottomEmojiTwo.setOnClickCallback {
            goToChat(it,binding.txtMatchSuccessBottomEmojiTwo.text.toString())
        }
        binding.txtMatchSuccessBottomEmojiThree.setOnClickCallback {
            goToChat(it,binding.txtMatchSuccessBottomEmojiThree.text.toString())
        }
        binding.txtMatchSuccessBottomEmojiFour.setOnClickCallback {
            goToChat(it,binding.txtMatchSuccessBottomEmojiFour.text.toString())
        }
        binding.txtMatchSuccessSend.setOnClickCallback {
            goToChat(it,binding.editMatchSuccessContent.text.toString())
        }
    }

    //跳转私信
    private fun goToChat(view: View,content:String?) {
        val context = activity ?: return
        shake(view, context)
        if (TextUtils.isEmpty(content)) {
            return
        }
        wlmViewModel.sendChatMessage(toUserId) {
            //如果成功,需要再调用一个open接口
            wlmViewModel.openChatPage(toUserId, 1)
            val conversationType: Conversation.ConversationType =
                Conversation.ConversationType.PRIVATE
            val messageContent = TextMessage.obtain(content)
            val message: Message = Message.obtain(toUserId, conversationType, messageContent)
            IMCenter.getInstance()
                .sendMessage(message, null, null, object : IRongCallback.ISendMessageCallback {
                    override fun onAttached(message: Message?) {}
                    override fun onSuccess(message: Message?) {
                        dismiss()
                    }

                    override fun onError(message: Message?, errorCode: RongIMClient.ErrorCode?) {}
                })
        }
    }


    private fun showAnim() {
        // 动画时间
        val animationDuration = 600L
        // 设置左侧 ImageView 的平移动画
        val leftAnimation = TranslateAnimation(
            -binding.imgMatchSuccessOne.width.toFloat(), 0f, // 从左侧平移到原位置
            0f, 0f
        ).apply {
            duration = animationDuration
            fillAfter = true
        }
        // 设置右侧 ImageView 的平移动画
        val rightAnimation = TranslateAnimation(
            binding.imgMatchSuccessTwo.width.toFloat(), 0f, // 从右侧平移到原位置
            0f, 0f
        ).apply {
            duration = animationDuration
            fillAfter = true
        }
        // 开始动画并设置 ImageView 可见
        binding.imgMatchSuccessOne.visibility = View.VISIBLE
        binding.imgMatchSuccessTwo.visibility = View.VISIBLE
        binding.imgMatchSuccessOne.startAnimation(leftAnimation)
        binding.imgMatchSuccessTwo.startAnimation(rightAnimation)

        // 加载动画
        val slideUp = AnimationUtils.loadAnimation(
            context,
            com.yoo.module_res.R.anim.anims_matchsuccess_slide_in_bottom
        )
        // 设置视图可见并开始动画
        binding.conMatchSuccessBottom.visibility = View.VISIBLE
        binding.conMatchSuccessBottom.startAnimation(slideUp)
        setData()
    }

    override fun onResume() {
        super.onResume()
        ImmersionBar.with(this).statusBarDarkFont(false).init()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.lottieMatchSuccessBg.cancelAnimation()
        innerBinding = null
        dismissAllowingStateLoss()
    }

    companion object {
        private const val MATCH_SUCCESS_TO_USER_ID = "MATCH_SUCCESS_TO_USER_ID"
        private const val MATCH_SUCCESS_TO_USER_HEAD = "MATCH_SUCCESS_TO_USER_HEAD"
        fun newInstance(imgUrl: String, toUserId: String): MatchSuccessDialogFragment {
            return MatchSuccessDialogFragment().apply {
                arguments = Bundle().apply {
                    putString(MATCH_SUCCESS_TO_USER_HEAD, imgUrl)
                    putString(MATCH_SUCCESS_TO_USER_ID, toUserId)
                }
            }
        }
    }

}